#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
    , ip("101.43.168.188")
    , port("19999")
{
    ui->setupUi(this);
    socket = new QTcpSocket;
}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_loginButton_clicked()
{
    //get username and password
    QString username = ui->usernameLineEdit->text();
    QString password = ui->passwordLineEdit->text();
    //connect to server
    QNetworkRequest request(QUrl("http://localhost:19999/slimarveous/login/"));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    QJsonObject json;
    json.insert("username", username);
    json.insert("password", password);
    QJsonDocument doc(json);

    QByteArray data = doc.toJson(QJsonDocument::Compact);
    QNetworkReply *reply = manager.post(request, data);
    connect(reply, &QNetworkReply::finished, [=]() {
        if (reply->error() == QNetworkReply::NoError) {
                // 读取响应数据
                QByteArray dataReply = reply->readAll();

                // 将 JSON 数据转换为 QVariant 对象
                QJsonParseError error;
                QJsonObject result = QJsonDocument::fromJson(dataReply, &error).object();
                // 处理 JSON 数据
                if (error.error == QJsonParseError::NoError) {
                    QVariantMap resultMap = result.toVariantMap();
                    if(resultMap.contains("user")) {
                        QMap userMap = resultMap.value("user").toMap();
                        QString id = userMap.value("id").toString();

                        userSelf.username = username;
                        userSelf.id = id;
                        QMessageBox::information(this, "login successful", "hello "+username+"! "+"your id is " +id);

                    }
                } else {

                }
            } else {
                qDebug()<<"error";
            }

            // 释放资源
            reply->deleteLater();
    });


}












